package executors;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;

import quasar.Station;
import quasar_framework.Common;

import tweeter.NetworkEntity;

public class PublicationsThread extends Thread
{
	private Boolean keepRunning = true;
	private ArrayList<Integer> publishers;
	private ArrayList<Station> stations;
	
	public PublicationsThread()
	{
		
	}
	
	public PublicationsThread(ArrayList<Integer> publishers, ArrayList<Station> stations)
	{
		this.publishers = publishers;
		this.stations = stations;
	}
	
	public void halt()
	{
		keepRunning = false;
	}
	
	@SuppressWarnings("static-access")
	public void run()
	{
		Random generator = new Random();
		int runningMessageID = 0;
		while (keepRunning)
		{
			HashSet<Integer> publishedIndexes = new HashSet<Integer>();
			for (int publishingIteration = 0 ; publishingIteration < Common.parallelPublishersNum ; publishingIteration++ )
			{
				int publisherIndex = generator.nextInt(publishers.size());
				while (publishedIndexes.contains(publisherIndex))
				{
					publisherIndex = generator.nextInt(publishers.size());
				}
				publishedIndexes.add(publisherIndex);
				int publisherID = publishers.get(publisherIndex);
				Station publisher = stations.get(publisherID);
				publisher.publish(runningMessageID++, null);
			}
			try
			{
				this.sleep(5000);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}
